package com.lfs.market.handler;

import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.function.Function;

public class ImageWriteHandler implements WriteHandler {

    private final int imageColumnIndex; // 图片插入的列索引（从0开始）
    private final Function<Object, byte[]> imageBytesFunction; // 获取图片字节数组的方法
    private final int rowIndexOffset; // 行偏移量，比如跳过标题行

    public ImageWriteHandler(int imageColumnIndex, Function<Object, byte[]> imageBytesFunction, int rowIndexOffset) {
        this.imageColumnIndex = imageColumnIndex;
        this.imageBytesFunction = imageBytesFunction;
        this.rowIndexOffset = rowIndexOffset;
    }

    public void beforeSheetCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
    }

    public void afterSheetCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
    }

    public void interceptWrite(List<List<String>> dataAll, int relativeRowIndex, WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        Sheet sheet = writeSheetHolder.getSheet();

        if (relativeRowIndex >= 0 && dataAll != null && !dataAll.isEmpty()) {
            Row row = sheet.getRow(relativeRowIndex + rowIndexOffset);
            if (row == null) row = sheet.createRow(relativeRowIndex + rowIndexOffset);

            Object data = dataAll.get(0); // 取第一个对象
            byte[] bytes = imageBytesFunction.apply(data);
            if (bytes != null && bytes.length > 0) {
                int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
                CreationHelper helper = workbook.getCreationHelper();
                Drawing<?> drawing = sheet.createDrawingPatriarch();

                // 设置图片锚点：插入到第 N 列，当前行
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(imageColumnIndex);
                anchor.setRow1(relativeRowIndex + rowIndexOffset);
                anchor.setCol2(imageColumnIndex + 1);
                anchor.setRow2(relativeRowIndex + rowIndexOffset + 1);

                Picture picture = drawing.createPicture(anchor, pictureIdx);
                picture.resize(); // 自动调整大小
            }
        }
    }

    // 下载图片为字节数组
    public static byte[] downloadImageBytes(String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) return new byte[0];
        try (InputStream in = new java.net.URL(imageUrl).openStream()) {
            return IOUtils.toByteArray(in);
        } catch (IOException e) {
            System.err.println("下载图片失败: " + imageUrl);
            e.printStackTrace();
            return new byte[0];
        }
    }
}